﻿//Thread
using System.ComponentModel;
using System.Diagnostics;

Stopwatch sw = new Stopwatch();

sw.Start();

for (int i = 0; i < 100; i++)
{
    //Thread th = new Thread(() =>
    //{

    //});
    Thread th = new Thread(_ =>  //"_":新语法糖弃元
    {

    });
    th.Start();
}

sw.Stop();
Console.WriteLine("耗时:" + sw.ElapsedMilliseconds + "ms");


Console.WriteLine("======================================================================");


//ThreadPool
sw.Restart();
for (int i = 0; i < 100; i++)
{
    ThreadPool.QueueUserWorkItem((s) =>
    {

    });
}
sw.Stop();
Console.WriteLine("耗时:" + sw.ElapsedMilliseconds + "ms");

Console.WriteLine("======================================================================");

//Task
Task.Run(() =>
{
    Console.WriteLine("Test");
});

Console.WriteLine("======================================================================");

//Parallel
String[] strs = { "Test1", "Test2", "Test3" };
//无顺序
Parallel.ForEach(strs, s => Console.WriteLine("线程id:"+Thread.CurrentThread.ManagedThreadId+","+s));

Console.WriteLine("======================================================================");

//BackgroundWorker
BackgroundWorker bg = new BackgroundWorker();
bg.DoWork += dowork1;
if (!bg.IsBusy)
{
    bg.RunWorkerAsync();
}

void dowork1(object? sender, DoWorkEventArgs e)
{
    Console.WriteLine("ThreadId:"+Thread.CurrentThread.ManagedThreadId);
    int sum = 0;
    for (int i = 0; i < 100; i++)
    {
        sum += i;
    }
    Console.WriteLine(sum);
    Console.WriteLine("ThreadId:"+Thread.CurrentThread.ManagedThreadId);
}

Console.ReadKey();

